<?php
namespace app\weapp\library;
use app\common\model\Department;
use app\common\model\Member;
use EasyWeChat\Work\Application;
use Throwable;
use think\facade\Log;
class WeAppApi{
    private $weApi;
    private $weApp;
    private $message;
    public function __construct($apiConf = []){
        $config = [
            'corp_id'=>'ww5d7b19c3c1ce8e1f',
            'secret' => 'Z7kR0_MhnYYq1VRC_6TfPGIiOnsBsyHw9s5_bdt9WnM',
            'token' => 'DGJ25KSmpioWpC12PfOnnLv',
            'aes_key' => '5Aot5xz53NdLsgtzoILpVDtytsYW4f5AgDOYekKdL5l',
            
          ];
        $app = new Application(array_merge($config,$apiConf));
        $this->weApp = $app;
        $this->weApi = $app->getClient();
    }

    public function sessioncode($code){
        try {
            $response = $this->weApi->post('https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session',[
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ]);
            if($response['errcode'] != 0){
                throw new \Exception($response['errmsg']);
            }
            return $response;
        } catch (\Throwable $th) {
            $this->message = $th->getMessage();
            return false;
        }
        
        return $response;
    }

    public function Message(){
        return $this->message;
    }
    //同步部门
    public function SyncGroup(){

        try {        
            $response =  $this->weApi->get('https://qyapi.weixin.qq.com/cgi-bin/department/list');
            $departmentArray = $response->toArray(false);
            if($response->isSuccessful()){
                
                $departmentData = [];
                foreach ($departmentArray['department'] as $key => $value) {
                    $departmentData[$key] = [
                        "id" => $value['id'],
                        "name" => $value['name'],
                        "parentid" => $value['parentid'],
                        "weigh" => $value['order'],
                        "department_leader" => $value['department_leader']?json_encode($value['department_leader']):"",
                    ];
                    if(empty(Department::find($value['id']))){
                        Department::create([
                        "id" => $value['id'],
                        "name" => $value['name'],
                        "parentid" => $value['parentid'],
                        "weigh" => $value['order'],
                        "department_leader" => $value['department_leader']?json_encode($value['department_leader']):"",
                    ]);
                    }
                }
                $department = new Department();
                $re = $department->saveAll($departmentData);
                
            }
            $this->message = $departmentArray['errmsg'];
            return false;
        } catch (\Throwable $th) {
            $this->message = $th->getMessage();
            return false;
        }
    }
    
    public function syncMember(){
        $response =  $this->weApi->get('https://qyapi.weixin.qq.com/cgi-bin/user/list_id');
        $departmentArray = $response->toArray(false);
        if($response->isSuccessful()){
            foreach ($departmentArray['dept_user'] as $key=>$value){
               $member =  Member::GetByUserId($value['userid']);
               if(empty($member)){
                  $member = new Member(); 
               }
               $member->user_id = $value['userid'];
               $member->department_id = $value['department'];
               $member->save();
            }
        }
        
    }
    //同步成员字段;
    public function SyncHrField(){
        
        try {
            $response =  $this->weApi->get('https://qyapi.weixin.qq.com/cgi-bin/hr/get_fields');
            $rlt = $response->toArray(false);
            if($response->isSuccessful()){
                return $rlt['group_list'];
            }
            $this->message = $rlt['errmsg'];
            return false;
        } catch (\Throwable $th) {
            $this->message = $th->getMessage();
            return false;
        }
        
        
    }
    //同步成员
    public function syncHrUser($userId){
            $response =  $this->weApi->postJson('https://qyapi.weixin.qq.com/cgi-bin/hr/get_staff_info',['userid'=>$userId,
                "fieldids"=>[
		        [ "fieldid"=>20001, "sub_idx"=>0],
                [ "fieldid"=>20003, "sub_idx"=>0],
                [ "fieldid"=>20004, "sub_idx"=>0],
                [ "fieldid"=>20006, "sub_idx"=>0],
                [ "fieldid"=>20008, "sub_idx"=>0],
                [ "fieldid"=>20009, "sub_idx"=>0],
                [ "fieldid"=>20010, "sub_idx"=>0],
                [ "fieldid"=>20011, "sub_idx"=>0],
                [ "fieldid"=>20012, "sub_idx"=>0],
                [ "fieldid"=>20013, "sub_idx"=>0],
                [ "fieldid"=>20014, "sub_idx"=>0],
                [ "fieldid"=>20015, "sub_idx"=>0],
                [ "fieldid"=>20016, "sub_idx"=>0],
                [ "fieldid"=>20017, "sub_idx"=>0],
                [ "fieldid"=>20018, "sub_idx"=>0],
                [ "fieldid"=>20019, "sub_idx"=>0],
                [ "fieldid"=>20020, "sub_idx"=>0],
	        ]
            
            ]);
            $rlt = $response->toArray();
            if($response->isSuccessful()){
                return $rlt;
            }
            $this->message = $rlt['errmsg'];
            return false;
       
    }
    public function AddGroup($data){
        try {
            $response =  $this->weApi->postJson('https://qyapi.weixin.qq.com/cgi-bin/department/create',$data);
            if($response->isSuccessful()){
                return true;
            }
            $rlt = $response->toArray(false);
            $this->message = $rlt['errmsg'];
            return false;
        } catch (\Throwable $th) {
            $this->message = $th->getMessage();
            return false;
        }
        
    }
    public function EditGroup($data){
        try {
            $response =  $this->weApi->postJson('https://qyapi.weixin.qq.com/cgi-bin/department/update',$data);
            if($response->isSuccessful()){
                return true;
            }
            $rlt = $response->toArray(false);
            $this->message = $rlt['errmsg'];
            return false;
        } catch (\Throwable $th) {
            $this->message = $th->getMessage();
            return false;
        }
    }


}